package zeroj.web.view.wrapper;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import zeroj.web.context.ValueStack;

/**
 * 
 * 
 * @author lyl(lylsir at gmail dot com)
 * @since 1.0
 * 
 * 2008-9-9
 */
public class HttpRequestWrapper extends HttpServletRequestWrapper {

	public static final String ValueStackKey = 
		ValueStack.class.getPackage() + "." + ValueStack.class.getName();
	
	public HttpRequestWrapper(HttpServletRequest request) {
		super(request);
	}
	
	public boolean isAjax() {
		
		return "XMLHttpRequest".equals(getHeader("HTTP_X_REQUESTED_WITH"));
	}

	@Override
	public String getRemoteAddr() {
		
		String ip = getHeader("X-Forwarded-For");
		try {
			if (ip == null)
				ip = super.getRemoteAddr();
			else {
				InetAddress addr = InetAddress.getByName(ip); 
				ip = addr.getHostAddress(); 
			}
		} catch (UnknownHostException e) { 
			ip = super.getRemoteAddr(); 
		}
		return ip;
	}
	public boolean isGet() {
		
		return "GET".equals(getMethod());
	}
	public boolean isPost() {
		
		return "POST".equals(getMethod());
	}
	public ValueStack getValueStack() {
		
		ValueStack stack = (ValueStack)getSession().getAttribute(ValueStackKey);
		if(stack == null) {
			stack = new ValueStack();
			getSession().setAttribute(ValueStackKey, stack);
		}
		return stack;
	}
	
}
